package com.mrjy.common.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.maintain.bo.IAdminAuthorityBo;
import com.mrjy.wechat.conts.WxConsts;

public class AdminSystemFilter implements Filter {
	
	private static WebApplicationContext applicationContext;

	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		ServletContext servletContext = fConfig.getServletContext();
		applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpServletResponse servletResponse = (HttpServletResponse) response;
		HttpSession session = servletRequest.getSession();

		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		IAdminAuthorityBo adminAuthorityBo = (IAdminAuthorityBo) applicationContext.getBean("adminAuthorityBo");
		if(userInfo != null){
			//servletRequest.getRequestURI()==> eg:/mrjy/admin/manager
			@SuppressWarnings("unchecked")
			Map<String, Object> returnMap = (Map<String, Object>) adminAuthorityBo.validateAuthToPath(userInfo.getRoleId(), servletRequest.getRequestURI());
			//权限匹配
			if(null !=returnMap && "200".equals(returnMap.get("err_code"))){
				chain.doFilter(request, response);
			}else{
				servletResponse.sendRedirect(WxConsts.PUBLIC_DOMAIN + "/admin/index.html");
			}
		}else{
			servletResponse.sendRedirect(WxConsts.PUBLIC_DOMAIN + "/admin/index.html");
		}
	}
	
	@Override
	public void destroy() {
	}

}
